import logging

from fastapi import APIRouter, Depends, Query

from app.core.deps import CurrentUser, get_current_user
from app.schemas.common import OrderSchema, PaginationParams, PaginationResult
from app.schemas.job import (
    ChangeLogFilters,
    ExecutionHistoryFilters,
    JobChangeLog,
    JobCreate,
    JobExecutionLog,
    JobItem,
    JobListFilters,
)
from app.schemas.response import Response
from app.services.scheduler.task_service import TaskService

logger = logging.getLogger(__name__)

router = APIRouter()
task_service = TaskService()


def get_job_order_schema(
    order_by: str = Query(
        "",
        description="排序字段，多个字段用逗号分隔，字段名前加-表示降序，如：-created_at,id。可用字段：id, name, status, created_at, updated_at",
    )
) -> OrderSchema:
    """获取任务排序Schema"""
    return OrderSchema.with_allowed_fields(
        allowed_fields={"id", "name", "status", "created_at", "updated_at"}, order_by=order_by
    )


def get_execution_history_order_schema(
    order_by: str = Query(
        "",
        description="排序字段，多个字段用逗号分隔，字段名前加-表示降序，如：-created_at,id。可用字段：id, job_id, status, created_at, finished_at",
    )
) -> OrderSchema:
    """获取执行历史排序Schema"""
    return OrderSchema.with_allowed_fields(
        allowed_fields={"id", "job_id", "status", "created_at", "finished_at"}, order_by=order_by
    )


def get_change_log_order_schema(
    order_by: str = Query(
        "",
        description="排序字段，多个字段用逗号分隔，字段名前加-表示降序，如：-created_at,id。可用字段：id, job_id, change_type, created_at",
    )
) -> OrderSchema:
    """获取变更记录排序Schema"""
    return OrderSchema.with_allowed_fields(
        allowed_fields={"id", "job_id", "change_type", "created_at"}, order_by=order_by
    )


@router.post("/create", response_model=Response[JobItem])
async def create_job(current_user: CurrentUser, job_create: JobCreate):
    """创建任务"""
    try:
        job = await task_service.create_job(job_create, current_user)
        return Response(data=job)
    except Exception as e:
        logger.error(f"创建任务失败: {str(e)}", exc_info=True)
        return Response.error()


@router.get("/list", response_model=Response[PaginationResult[JobItem]])
async def list_jobs(
    current_user: CurrentUser,
    filters: JobListFilters = Depends(),
    order: OrderSchema = Depends(get_job_order_schema),
    pagination: PaginationParams = Depends(),
):
    """获取任务列表"""
    try:
        result = await task_service.list_jobs(filters, order, pagination)
        return Response(data=result)
    except Exception as e:
        logger.error(f"获取任务列表失败: {str(e)}", exc_info=True)
        return Response.error()


@router.get("/history/list", response_model=Response[PaginationResult[JobExecutionLog]])
async def list_execution_histories(
    current_user: CurrentUser,
    filters: ExecutionHistoryFilters = Depends(),
    order: OrderSchema = Depends(get_execution_history_order_schema),
    pagination: PaginationParams = Depends(),
):
    """获取执行历史列表"""
    try:
        result = await task_service.list_execution_history(filters, order, pagination)
        return Response.success(data=result)
    except Exception as e:
        logger.error(f"获取执行历史列表失败: {str(e)}", exc_info=True)
        return Response.error()


@router.get("/log/list", response_model=Response[PaginationResult[JobChangeLog]])
async def list_change_logs(
    current_user: CurrentUser,
    filters: ChangeLogFilters = Depends(),
    order: OrderSchema = Depends(get_change_log_order_schema),
    pagination: PaginationParams = Depends(),
):
    """获取变更记录列表"""
    try:
        result = await task_service.list_change_logs(filters, order, pagination)
        return Response.success(data=result)
    except Exception as e:
        logger.error(f"获取变更记录列表失败: {str(e)}", exc_info=True)
        return Response.error()
